package org.hcyspartnoc.luoxin.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.hcyspartnoc.luoxin.common.core.configuration.AliyunConfiguration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Objects;

@Component
public class AliyunOssUtils {
    private static AliyunConfiguration aliyunConfiguration;


    @Resource
    public void setAliyunConfiguration(AliyunConfiguration aliyunConfiguration) {
        AliyunOssUtils.aliyunConfiguration = aliyunConfiguration;
    }

    public String upload(byte[] bytes, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = getOssClient();
        try {
            // 创建PutObject请求。
            ossClient.putObject(aliyunConfiguration.getOss().getBucketName(), objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException | ClientException oe) {
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return generateUrl(objectName);
    }

    private OSS getOssClient() {
        return new OSSClientBuilder().build(aliyunConfiguration.getOss().getEndpoint(),
                aliyunConfiguration.getAccessKeyId(), aliyunConfiguration.getAccessKeySecret());
    }

    public String generateUrl(String objectName) {
        OSS ossClient = getOssClient();
        try {
            Date expiration = new Date(System.currentTimeMillis() + aliyunConfiguration.getOss().getExpireTime() * 1000);
            return ossClient.generatePresignedUrl(aliyunConfiguration.getOss().getBucketName(), objectName, expiration).toString();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public boolean objectIsExists(String objectName) {
        if (Objects.isNull(objectName) || objectName.isEmpty())
            return false;
        OSS ossClient = getOssClient();
        try {
            return ossClient.doesObjectExist(aliyunConfiguration.getOss().getBucketName(), objectName);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
